package com.aiapphub.BaseCode.service.impl;

import com.aiapphub.BaseCode.entity.Role;
import com.aiapphub.BaseCode.mapper.RoleMapper;
import com.aiapphub.BaseCode.service.RoleService;
import com.aiapphub.BaseCode.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Override
    public PageVo getPageList(Integer page, Integer limit, Map<String, Object> searchObj) {
        // 创建分页对象
        Page<Role> pageParam = new Page<>(page, limit);
        
        // 创建查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        
        // 如果有搜索条件，添加到查询中
        if (searchObj != null) {
            String roleName = (String) searchObj.get("roleName");
            if (roleName != null && !roleName.isEmpty()) {
                queryWrapper.like("role_name", roleName);
            }
        }
        
        // 添加删除标记过滤
        queryWrapper.eq("is_deleted", 0);
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc("create_time");
        
        // 执行分页查询
        baseMapper.selectPage(pageParam, queryWrapper);
        
        // 构造返回结果
        PageVo pageVo = new PageVo();
        pageVo.setList(pageParam.getRecords());
        pageVo.setTotal(pageParam.getTotal());
        
        return pageVo;
    }

    @Override
    public Role getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean saveRole(Role role) {
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        role.setIsDeleted(0);
        return save(role);
    }

    @Override
    public boolean updateRole(Role role) {
        role.setUpdateTime(new Date());
        return updateById(role);
    }

    @Override
    public boolean removeRole(Long id) {
        // 硬删除：直接从数据库中删除记录
        return this.removeById(id);
    }

    @Override
    public boolean batchRemoveRoles(Long[] ids) {
        // 批量硬删除：直接从数据库中删除多条记录
        return this.removeByIds(Arrays.asList(ids));
    }
}